package wbbs.service;

import javax.sql.DataSource;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class Utils {

    private static MessageDigest md5;

    static {
        try {
            md5 = MessageDigest.getInstance("md5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static byte[] md5(String pwd) {
        try {
            return md5.digest(pwd.getBytes("iso8859-1"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static void ensureDB(DataSource ds) {
        try {
            Connection con = ds.getConnection();
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("show tables");
            boolean needCreate = !rs.next();
            rs.close();
            if (needCreate) {
                StringBuilder sb = new StringBuilder();
                InputStreamReader reader = new InputStreamReader(Utils.class.getResourceAsStream("init.sql"));
                char[] buf = new char[1024];
                int rd;
                while ((rd = reader.read(buf)) != -1) {
                    sb.append(buf, 0, rd);
                }
                reader.close();
                for (String s : sb.toString().split(";")) {
                    if ((s = s.trim()).isEmpty()) continue;
                    stmt.execute(s);
                }
                PreparedStatement pstmt = con.prepareStatement("insert into User(id, pwd, name, head) values('admin', ?, '站长', '/head/1.jpg')");
                pstmt.setBytes(1, md5("admin"));
                pstmt.execute();
                stmt.close();
                stmt = pstmt;
            }
            stmt.close();
            con.close();
        } catch (Exception e) {
            throw new RuntimeException("create db failed", e);
        }
    }
}
